package com.example.shirospringboot.config;

import com.example.shirospringboot.pojo.User;
import com.example.shirospringboot.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        //simpleAuthorizationInfo.addStringPermission("user:add");

        //拿到当前登录对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//拿到User

        //设置当前用户的权限
        if(!"".equals(currentUser.getPerms())){
            simpleAuthorizationInfo.addStringPermission(currentUser.getPerms());
        }

        return simpleAuthorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>授权doGetAuthenticationInfo");


        //用户名，密码
        String name="root";
        String password="123456";

        UsernamePasswordToken userToken=(UsernamePasswordToken)authenticationToken;

        //连接真实数据库
        //User user = userService.queryUserByName(userToken.getUsername());

//        if (!user.getUsername().equals(name)){
//            return null;//抛出异常UnknownAccountException
//        }
//        if(user==null){//没有此人
//            return null;
//        }

        //密码认证shiro做
        return new SimpleAuthenticationInfo("",password,"");

    }
}
